package cn.xspace.module.other.activity;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.LogUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.module.other.R;
import cn.xspace.module.other.util.RProxy;
import cn.xspace.module.other.view.adapter.PlaceSetAdapter;
import cn.xspace.wnx.entity.AreaBean;
import cn.xspace.wnx.util.ShareUtils;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * @version V1.0.0
 * @ClassName: QuestionPlaceAct
 * @author:guankui
 * @Date：2014年2月21日
 * @Description: 地区显示
 */
public class PlaceSetAct extends BaseActivity {

    public static final String TAG = PlaceSetAct.class.getSimpleName();

    public ListView listView;

    public static final int PROGRESS_STATUS_FETCH_VERIFYCODE = 1;
    public static final int PLACE_FORREULR = 8;// 地区返回值
    private PlaceSetAdapter mAdapter;
    //    public List<PlaceSetBean> mList = new ArrayList<PlaceSetBean>();
    public List<AreaBean> mList = new ArrayList<>();
    public int list_flag = 0;
    public String place, place_id;
    public ArrayList<String> list_id = new ArrayList<>();
    private MyHandler mHandler = new MyHandler();
    private boolean ishowcheck;
    private boolean isFromUserInfo;
    int areaCodeLength = 0;
    //    QueryUnionAreaImpl queryUnionArea;
    private Context mContext;

    private int index = 0;  // 保存地区
    private String area_code;
    private List<AreaBean> mTownsList;

    @Override
    protected void initView() {
        setContentView(R.layout.questionplaceact);
    }

    @Override
    protected void initData() {
        mContext = this;
        area_code = MyInfoUtil.getAppDeptAreaCode();
    }

    @Override
    protected void initFindViewById() {
        listView = (ListView) findViewById(RProxy.listview);
    }

    @Override
    protected void getIntentData() {
        ishowcheck = getIntent().getBooleanExtra("ishowcheck", false);
        isFromUserInfo = getIntent().getBooleanExtra("isFromUserInfo", false);
        areaCodeLength = getIntent().getIntExtra("areaCodeLength", 6);
    }

    @Override
    protected void initEvent() {
        list_id.add("");
        if (isFromUserInfo) {
            area_code = "0";
        } else {
            if (area_code == null) {
                area_code = "0";
            }
        }
        requestTownsList(area_code);
//        setTitleBarBg(findViewById(R.id.r_item));
        findViewById(R.id.questionplaceact_up_btn)
                .setVisibility(View.VISIBLE);
    }

//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//
//        if (ishowcheck && !isFromUserInfo) {
//            queryUnionArea = new QueryUnionAreaImpl();
//        }
//        init();

//        initData(area_code);
//        Log.v("palceSet", "PlaceSetAct onCreate>>");
//    }

//    /**
//     * @param
//     * @return
//     * @throws
//     * @Description: 初始化界面
//     */
//    private void init() {
//    }

    /**
     * @param
     * @return
     * @throws
     * @Description: 获取问题种类
     */
//    private void initData(String disid) {
//        Log.v("palceSet", "initData disid:" + disid);
//        showDialog(getString(RProxy.dialog_get_place));
////        if (queryUnionArea != null) {
//        if ("0".equals(disid)) disid = "";
//        queryUnionArea.sendQueryUnionArea(disid, new IQueryUnionArea() {
//
//            @Override
//            public void onQueryUnionArea(String code, List<MAreaBean> datalist) {
//                cancelDialog();
//                if (datalist != null && datalist.size() > 0) {
//                    mList.clear();
//                    for (int i = 0; i < datalist.size(); i++) {
//                        MAreaBean mab = datalist.get(i);
////                            PlaceSetBean psb = new PlaceSetBean();
//                        AreaBean areaBean = new AreaBean();
//                        areaBean.area_code = mab.id;
//                        areaBean.area_name = mab.name;
//                        areaBean.isLeaf = mab.isleaf;
//                        mList.add(areaBean);
//                    }
//                    mHandler.sendEmptyMessage(0);
//                } else {
//
//                }
//            }
//        });
//        } else {
//        new PlaceSetMgImpl(PlaceSetAct.this).placeRequest(disid,
//                new IPlaceSetRequest() {
//                    @Override
//                    public void onResult(List<AreaBean> returnList) {
//                        cancelDialog();
//                        if (returnList != null && returnList.size() > 0) {
//                            mList = returnList;
//                            mHandler.sendEmptyMessage(0);
//                        } else {
//                            Toast.makeText(getApplicationContext(),
//                                    RProxy.network_fail, Toast.LENGTH_SHORT)
//                                    .show();
//                        }
//                    }
//                });
//        }
//    }


    /**
     * @param
     * @return
     * @throws
     * @Description: listView 绑定adapter，点击事件监听处理
     */
    private void listViewControl() {
        mAdapter = new PlaceSetAdapter(PlaceSetAct.this, mList, ishowcheck);
        listView.setDivider(null);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                if ("0".equalsIgnoreCase(mList.get(arg2).isLeaf)) {
                    LogUtil.e("PlaceSetActivity   ====== mList:" + mList.get(arg2).toString());
                    ShareUtils.put(mContext, "page" + index, mList.get(arg2).area_code + "");
                    index++;
                    String areacode = mList.get(arg2).area_code;
                    if (!TextUtils.isEmpty(areacode)) {
                        if (areacode.length() >= areaCodeLength && ishowcheck) {
                            place = mList.get(arg2).area_name;
                            place_id = mList.get(arg2).area_code;
                            returnType();
                        } else {
//                            initData(mList.get(arg2).areacode);
                            requestTownsList(mList.get(arg2).area_code);
                            list_id.add(mList.get(arg2).area_code);
                            mAdapter = new PlaceSetAdapter(PlaceSetAct.this, mList, ishowcheck);
                            mAdapter.notifyDataSetChanged();
                            list_flag = 1;
                        }
                    } else {
                        place = mList.get(arg2).area_name;
                        place_id = mList.get(arg2).area_code;
                        returnType();
                    }
                } else {   // 只有在没有子节点的时候才会走
                    place = mList.get(arg2).area_name;
                    place_id = mList.get(arg2).area_code;
                    LogUtil.e("PlaceSetActivity   ====== mList:" + mList.get(arg2).toString());
                    String areacode = mList.get(arg2).area_code;
                    if (areacode.equals("81") || areacode.equals("71"))
                        ShareUtils.remove(mContext, "page0");
                    ShareUtils.put(mContext, "lastPage", areacode);
                    returnType();
                }

            }

        });

    }

    /**
     * @param
     * @return
     * @throws
     * @Description: 返回最终数据
     */
    public void returnType() {
//		Intent intent = new Intent();
//		intent.putExtra("Place", place);// 把返回数据存入Intent
//		intent.putExtra("PlaceCode", place_id);// 把返回数据存入Intent
        /**
         * @author wangtao
         * eventbus
         */
//		setResult(UserInfoAct.PLACESET_FORREULR, intent);
        Map map = new HashMap();
        map.put("type", "PlaceSetAct");
        map.put("Place", place);
        map.put("PlaceCode", place_id);
        EventBus.getDefault().post(map);
        finish();

    }

    /**
     * @param
     * @return
     * @throws
     * @Description: 界面点击事件监听方法 （xml定义）
     */
    public void onClick(View view) {
        if (view.getId() == R.id.btn_return) {
            finish();
        }
        if (view.getId() == R.id.questionplaceact_up_btn) {
            index--;
            int length = list_id.size();
            if (length > 0) {
                list_id.remove(length - 1);
            }
            for (String id : list_id) {
                Log.v("palceSet", "list_id:" + id);
            }
            int newSize = list_id.size();
            if (newSize > 1) {
//                initData(list_id.get(newSize - 1));
                requestTownsList(list_id.get(newSize - 1));
                //	list_id.remove(length - 1);
            } else {
//                initData("0");
                requestTownsList("0");
            }
        }
    }

    public class MyHandler extends Handler {
        public void handleMessage(android.os.Message msg) {
            listViewControl();

        }

    }

    private void requestTownsList(String disid) {
        showWaitDialog();
        HashMap<String, Object> map = new HashMap<>();
        if ("0".equals(disid)) disid = "";
        String query_plat = "common";
        map.put("query_plat", query_plat);
        map.put("area_code", disid);
//        map.put("area_code", serviceObjBean.user_qucode); //该id为空时进不了该方法
        OkHttpManager.getInstance().commonRequest(Constants.QUERY_AREA, map)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<AreaBean>>() {
                    @Override
                    public List<AreaBean> call(BaseReturnBean baseReturnBean) {
                        return new Gson().fromJson(baseReturnBean.data, new
                                TypeToken<List<AreaBean>>() {
                                }.getType());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<AreaBean>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(List<AreaBean> newList) {
                        hideWaitDialog();
                        mList.clear();
                        mTownsList = new ArrayList<>();
                        mTownsList.addAll(newList);
                        mList.addAll(mTownsList);
                        mHandler.sendEmptyMessage(0);
                        LogUtil.e("PlaceSetAct      ========   " + mTownsList.toString());
                    }
                });
    }
}
